package org.graysblog.dinojs.runner;

import java.io.FileInputStream;
import java.util.Properties;

import org.graysblog.dinojs.rhino.RhinoScriptRunner;

public class Runner {

	/**
	 * Dino Javascript
	 * Main Runner
	 * 
	 * @author: gray
	 * @category: main
	 * @param: Pass the application.properties file location
	 */
	
	public static String RuntimeVersion = "0.1";
	
	public static boolean PropsLoaded = false;
	
	public static Properties RunnerProps = null;
	
	public static String AppPath = null;
	
	public static void main(String[] args) {
		
		/* TODO: Work on main runner, initialize Rhino */
		
		try {
		
		System.out.println("DinoJS: Starting Initialization..");
		
		if (args != null) {
		
			if (args[0] != null) {
			
				/* Load properties file from that path */
			
				System.out.println("Application Properties Located at:"+args[0]);
			
				
				/* Load the properties */
				
				RunnerProps = new Properties();
				
				if (args[1] != null) {
					
					RunnerProps.load(new FileInputStream(args[0]+args[1]));
					
				} else {
				
					RunnerProps.load(new FileInputStream(args[0]+"application.properties"));
				
				}
				
				PropsLoaded = true;
				
				AppPath = args[0];
				
				}
				
			} else {
				System.out.println("Error! Cannot start runner, no application.properties path passed!");
			}
		
		
		
		} catch (Exception e) {
			
			System.out.println("Exception in Runner! Exception Message:"+e.getMessage());
			
		}
		
		/* Loaded properties file? */
		
		if (PropsLoaded) {
			System.out.println("Properties file loaded successfully!");
			
			String RuntimeVersion = RunnerProps.getProperty("runtimeVersion");
			
			if (RuntimeVersion.equals(RuntimeVersion)) {
				
				/* Runtime version is up to date with the current one */
				
				System.out.println("Loaded Application!");
				
				System.out.println("Application Name:"+RunnerProps.getProperty(Constants.ApplicationTitleKey));
				System.out.println("Application Version:"+RunnerProps.getProperty(Constants.ApplicationVersionKey));
				System.out.println("Application Author:"+RunnerProps.getProperty(Constants.ApplicationAuthorKey));
				
				/* Try to run the app */
				
				RhinoScriptRunner ScriptRunner = new RhinoScriptRunner();
				
				ScriptRunner.RunFile(RunnerProps, AppPath);
				
			} else {
				
				System.out.println("Application runtime version different, cannot run!");
			
			}
		}
		
		
		
	}

}
